package com.service.sys;

import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;

@Service
public class SysLogService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public int add(String creator, String creatorname, String createinfo, String table, String row, String col,
			String act) {
		String sql = "insert into sys_log(LOG_CREATEORID,LOG_CREATEORNAME,LOG_CREATETIME,LOG_CREATEINFOR,LOG_SOURSETABLE,LOG_SOURSEROW,LOG_SOURSECOL,LOG_ACTION) values(?,?,?,?,?,?,?,?)";
		DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String czsj = format1.format(new Date());
		// sql = MessageFormat.format(sql, czr, cznr, czsj);
		System.out.println("syslog:" + sql);
		return jdbcTemplate.update(sql, creator, creatorname, czsj, createinfo, table, row, col, act);
	}

	public void addBatch(List<Object[]> batchArgs) {
		String sql = "insert into sys_log(czr,cznr,czsj) values(?,?,?)";
		jdbcTemplate.batchUpdate(sql, batchArgs);
	}

	public void batchUpdateLinkset(final List<Object[]> list) {
		String sql = "insert into sys_log(czr,cznr,czsj) values(?,?,?)";
		jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public int getBatchSize() {
				// 这个方法设定更新记录数，通常List里面存放的都是我们要更新的，所以返回list.size();
				return list.size();
			}

			@Override
			public void setValues(java.sql.PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.getConnection().setAutoCommit(false);
				ps.setString(1, (String) list.get(i)[0]);
				ps.setString(2, (String) list.get(i)[1]);
				ps.setString(3, (String) list.get(i)[2]);

			}

		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void batchUpdate() {
		String sql = "insert into sys_log(czr,cznr,czsj) values(?,?,?)";
		jdbcTemplate.execute(sql, new PreparedStatementCallback() {

			@Override
			public Object doInPreparedStatement(java.sql.PreparedStatement ps)
					throws SQLException, DataAccessException {
				for (int i = 0; i < 10000; i++) {
					ps.setString(1, "1");
					ps.setString(2, "1");
					ps.setString(3, "");
					ps.addBatch();
				}
				ps.executeBatch(); // 数据不会持久化到数据库中
				return null;
			}
		});
	}
}
